﻿using Genespy.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Threading;
using System.Threading.Tasks;
using Bing.Maps;
using Windows.Devices.Geolocation;
using System.ComponentModel;
// The Hub Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=286574

namespace Genespy
{
    /// <summary>
    /// A page that displays a grouped collection of items.
    /// </summary>
    public sealed partial class MainPage : Page,INotifyPropertyChanged
    {
        private NavigationHelper navigationHelper;
        private ObservableDictionary defaultViewModel = new ObservableDictionary();
        private GenespySavedData _genesySavedData;        
        private bool _isSearchSelected;
        private List<Report> _searchResults;
        private string _searchQuery;
        private Report _selectedReport; 
        public static Report selectedReport;
        private ListView FieldReportsUI;
        private ListView SearchFieldReportsUI;
        private TextBox SearchBoxUI;
        private Pushpin pin;
        private Geolocator geolocator;
        private CancellationTokenSource cts;
        private LocationIcon10m locationIcon10m;
        private LocationIcon100m locationIcon100m;
        private bool onPage;
        private Timer timer;

        public bool IsSearchSelected
        {
            get { return _isSearchSelected; }
            set
            {
                if (_isSearchSelected != value)
                {
                    _isSearchSelected = value;
                    OnPropertyChanged("IsSearchSelected");
                }
            }
        }

        public List<Report> reports
        {
            get { return GenespySavedData.Data; }
            set
            {
                if (GenespySavedData.Data != value)
                {
                    GenespySavedData.Data = value;
                    OnPropertyChanged("reports");
                }
            }
        }

        public GenespySavedData GenespySavedData
        {
            get { return _genesySavedData; }
            set
            {
                if (_genesySavedData != value)
                {
                    _genesySavedData = value;
                    OnPropertyChanged("GenespySavedData");
                }
            }
        }
        public List<Report> searchResult
        {
            get { return _searchResults; }
            set
            {
                if (_searchResults != value)
                {
                    _searchResults = value;
                    OnPropertyChanged("searchResult");
                }
            }
        }
        public string searchQuery
        {
            get { return _searchQuery; }
            set
            {
                if (_searchQuery != value)
                {
                    _searchQuery = value;
                    OnPropertyChanged("searchQuery");
                }
            }
        }
        public Report loaclSelectedReport {
            get { return _selectedReport; }
            set
            {
                if (_selectedReport != value)
                {
                    _selectedReport = value;
                    selectedReport = value;
                    OnPropertyChanged("loaclSelectedReport");
                }
            }
        }
        /// <summary>
        /// This can be changed to a strongly typed view model.
        /// </summary>
        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        /// <summary>
        /// NavigationHelper is used on each page to aid in navigation and 
        /// process lifetime management
        /// </summary>
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }

        public MainPage()
        {
            this.InitializeComponent();
            geolocator = new Geolocator();
            SearchView.Visibility = Visibility.Collapsed;          
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += navigationHelper_LoadState;

            locationIcon10m = new LocationIcon10m();
            locationIcon100m = new LocationIcon100m();
            onPage = true;

            CreateTimer();
         }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            // TODO: Assign a collection of bindable groups to this.DefaultViewModel["Groups"]   
        }

        #region NavigationHelper registration

        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// 
        /// Page specific logic should be placed in event handlers for the  
        /// <see cref="GridCS.Common.NavigationHelper.LoadState"/>
        /// and <see cref="GridCS.Common.NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method 
        /// in addition to page state preserved during an earlier session.

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedTo(e);
            onPage = true;
            addCurrentLocation();
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedFrom(e);
            onPage = false;
        }

        #endregion

        private void move_to_report()
        {
            if(this.Frame != null)
            {
                this.Frame.Navigate(typeof(ReportPage));
            }
        }
        private void on_search_Results(object sender, TappedRoutedEventArgs e)
        {
            if(searchQuery!= null){
                foreach(Report report in reports){
                    if(report.title.Contains(searchQuery)){
                        searchResult.Add(report); 
                    }
                }            
            }
        }
        private void on_back_pressed(object sender, TappedRoutedEventArgs e)
        {
            SearchView.Visibility = Visibility.Collapsed;
            recentReportsView.Visibility = Visibility.Visible; 
        }
        private void on_tap_openSearchSection(object sender, TappedRoutedEventArgs e)
        {
            recentReportsView.Visibility = Visibility.Collapsed;
            SearchView.Visibility = Visibility.Visible; 

        }
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(String propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        private void on_click_create_report(object sender, RoutedEventArgs e)
        {
            Report newReport = new Report();
            GenespySavedData.Data.Add(newReport);
            selectedReport = newReport;

            if (this.Frame != null)
            {
                this.Frame.Navigate(typeof(ReportPage));
            }
        }

        private TextBlock reportUIBuilder(Report report)
        {
            TextBlock reportTitle = new TextBlock();
            TextBlock reportDate = new TextBlock();

            //Windows.UI.Text.FontWeight font = new Windows.UI.Text.FontWeight();
            //font.Weight = 40;

            //reportTitle.Foreground = new SolidColorBrush(Windows.UI.Colors.White);
            //reportTitle.FontWeight = font;
            reportTitle.Text = report.title + " - " + report.date.ToString();

            reportTitle.Style = Resources["BodyTextBlockStyle"] as Style;

            return reportTitle;
            //reportDate.Foreground = new SolidColorBrush(Windows.UI.Colors.White);
            //reportDate.FontWeight = font;
            //reportDate.Text = report.date.ToString();
        }

        private void on_field_reports_loaded(object sender, RoutedEventArgs e)
        {
            FieldReportsUI = sender as ListView;

            foreach (Report report in GenespySavedData.Data)
            {
                FieldReportsUI.Items.Add(reportUIBuilder(report));
            }
        }

        private void on_field_report_selected(object sender, SelectionChangedEventArgs e)
        {
            selectedReport = GenespySavedData.Data.ElementAt(FieldReportsUI.SelectedIndex);
            move_to_report();
        }

        private void on_search_field_reports_loaded(object sender, RoutedEventArgs e)
        {
            SearchFieldReportsUI = sender as ListView;
        }

        private void on_search_text_change(object sender, TextChangedEventArgs e)
        {
            SearchFieldReportsUI.Items.Clear();

            foreach (Report report in reports)
            {
                if (report.title.Contains(SearchBoxUI.Text))
                {
                    SearchFieldReportsUI.Items.Add(reportUIBuilder(report));
                }
            }          
        }

        private void on_search_text_loaded(object sender, RoutedEventArgs e)
        {
            SearchBoxUI = sender as TextBox;           
        }

        //Pro Shout out http://msdn.microsoft.com/en-us/library/windows/apps/jj850315.aspx
        private async void addCurrentLocation()
        {
            if(onPage)
            { 
                pin = new Pushpin();
                pin.Text = "007";

                cts = new CancellationTokenSource();
                CancellationToken token = cts.Token;

                Geoposition pos = await geolocator.GetGeopositionAsync().AsTask(token);
                Location location = new Location(pos.Coordinate.Latitude, pos.Coordinate.Longitude);
                MapLayer.SetPosition(pin, location);
                agentLocationMap.Children.Add(pin);

                // Now set the zoom level of the map based on the accuracy of our location data.
                // Default to IP level accuracy. We only show the region at this level - No icon is displayed.
                double zoomLevel = 13.0f;

                // if we have GPS level accuracy
                if (pos.Coordinate.Accuracy <= 10)
                {
                    // Add the 10m icon and zoom closer.
                    agentLocationMap.Children.Add(locationIcon10m);
                    MapLayer.SetPosition(locationIcon10m, location);
                    zoomLevel = 15.0f;
                }
                // Else if we have Wi-Fi level accuracy.
                else if (pos.Coordinate.Accuracy <= 100)
                {
                    // Add the 100m icon and zoom a little closer.
                    agentLocationMap.Children.Add(locationIcon100m);
                    MapLayer.SetPosition(locationIcon100m, location);
                    zoomLevel = 14.0f;
                }

                // Set the map to the given location and zoom level.
                agentLocationMap.SetView(location, zoomLevel);
            }
        }

        //Pro shout out http://msdn.microsoft.com/en-us/library/system.threading.timer(v=vs.110).aspx
        private void CreateTimer()
        {
            //timer = new Timer(addCurrentLocation, null, 1000, 10000);
        }
    }
}
    
    
